package com.qianfeng.controller;


import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	
	@RequestMapping("/index")
	public String toUpload() {
		return "upload";
	}
	
	@RequestMapping("/indexs")
	public String toUploads() {
		return "uploads";
	}
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	@ResponseBody
	public String uploadFile(MultipartFile file,HttpServletRequest request) { //形参file要与<input type="file" name="file" />中name的值一样
		
		try {
			//创建文件在服务器端的存放路径
			String dir=request.getServletContext().getRealPath("/upload");
			System.out.println("dir is:"+dir); 
			File fileDir = new File(dir);
			if(!fileDir.exists()) {
				fileDir.mkdir();
			}
			System.out.println("fileDir is:"+fileDir);
			
			//生成文件在服务器端存放的名字
			//截取文件的拓展名
			String fileSuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			//为文件起一个不会重名的名字
			String fileName=UUID.randomUUID().toString()+fileSuffix;
			File files=new File(fileDir+"/"+fileName);
			
			//上传
			file.transferTo(files);
			System.out.println("success...");
			
			
		}catch(Exception e) {
			e.printStackTrace();
			return "上传失败";
		}
		
		return "上传成功";
	}
	
	
	@RequestMapping(value="/upload/batch", method=RequestMethod.POST)
	@ResponseBody
	public String uploadFiles(MultipartFile[] file,HttpServletRequest request) { //形参file要与<input type="file" name="file" />中name的值一样
		
		try {
			//创建文件在服务器端的存放路径
			String dir=request.getServletContext().getRealPath("/upload");
			File fileDir = new File(dir);
			if(!fileDir.exists()) {
				fileDir.mkdir();
			}
			for(int i=0;i<file.length;i++) {
				
					
					//生成文件在服务器端存放的名字
					//截取文件的拓展名			
					String fileSuffix=file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("."));
					//为文件起一个不会重名的名字
					String fileName=UUID.randomUUID().toString()+fileSuffix;
					File files=new File(fileDir+"/"+fileName);
					
					//上传
					file[i].transferTo(files);//将原来的文本内容拷贝到新建的文件中
				
			}
			
			
			
		}catch(Exception e) {
			e.printStackTrace();
			return "上传失败";
		}
		
		return "上传成功";
	}
}
